<template>
  <div class="home-container">
    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 网站信息卡片 -->
      <div class="info-card">
        <h1 class="site-title">课程学习网站</h1>
        <p class="site-description">欢迎来到数字化成长空间，探索各类优质课程资源</p>
        <div class="repository-info">
          <p>代码仓库：<a href="https://gitee.com/liu-meixi_0/learning-website.git" target="_blank">https://gitee.com/liu-meixi_0/learning-website.git</a></p>
        </div>
      </div>

      <!-- 课程类别卡片 -->
      <div v-if="categories && categories.length > 0" class="categories-section">
        <h2 class="section-title">课程类别</h2>
        <div class="categories-grid">
          <CategoryCard 
            v-for="(category, index) in displayedCategories" 
            :key="category.id"
            :category="category"
            :index="index"
            :course-count="getCategoryCourseCount(category.id)"
            @click="filterCoursesByCategory"
          />
        </div>
      </div>

      <!-- 课程列表 -->
      <div v-if="courses && courses.length > 0" class="courses-section">
        <div class="section-header">
          <h2 class="section-title">{{ currentCategory ? currentCategory.title : '全部课程' }}</h2>
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="最新添加" value="addedTime"></el-option>
            <el-option label="开始时间" value="startTime"></el-option>
          </el-select>
        </div>
        
        <div class="courses-grid">
          <CourseCard 
            v-for="course in displayedCoursesWithCategoryTitle"
            :key="course.id"
            :course="course"
          />
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredCourses.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>

      <!-- 无课程提示 -->
      <div v-else class="empty-state">
        <el-empty description="暂无课程数据" />
        <el-button type="primary" @click="$router.push('/add-course')">添加第一门课程</el-button>
      </div>
    </main>
  </div>
</template>

<script>
import { courseAPI, categoryAPI } from '../api'
import { ElMessage } from 'element-plus'
import CourseCard from '../components/CourseCard.vue'
import CategoryCard from '../components/CategoryCard.vue'

export default {
  name: 'HomeView',
  components: {
    CourseCard,
    CategoryCard
  },
  data() {
    return {
      courses: [],
      categories: [],
      currentCategory: null,
      sortBy: 'addedTime',
      currentPage: 1,
      pageSize: 8,
      displayedCategories: [],
      displayedCourses: []
    }
  },
  computed: {
    isLoggedIn() {
      return !!localStorage.getItem('token')
    },
    filteredCourses() {
      if (!this.courses) return []
      
      let filtered = [...this.courses]
      
      // 按类别过滤
      if (this.currentCategory && this.currentCategory.id) {
        filtered = filtered.filter(course => course.categoryid === this.currentCategory.id)
      }
      
      // 排序
      filtered.sort((a, b) => {
        const timeA = new Date(a[this.sortBy]).getTime()
        const timeB = new Date(b[this.sortBy]).getTime()
        return timeB - timeA // 降序排列
      })
      
      return filtered
    },
    displayedCoursesWithCategoryTitle() {
      // 为每个课程添加类别名称
      return this.displayedCourses.map(course => ({
        ...course,
        categoryTitle: this.getCategoryName(course.categoryid)
      }))
    }
  },
  async mounted() {
    await this.loadData()
  },
  
  // 添加activated钩子，确保每次组件激活时都重新加载数据
  async activated() {
    await this.loadData()
  },
  methods: {
    async loadData() {
      try {
        // 加载课程和类别数据
        const [coursesResponse, categoriesResponse] = await Promise.all([
          courseAPI.getAllCourses(),
          categoryAPI.getAllCategories('课程')
        ])
        
        this.courses = coursesResponse || []
        this.categories = categoriesResponse || []
        
        // 限制显示4个类别
        this.displayedCategories = this.categories.slice(0, 4)
        
        // 更新显示的课程
        this.updateDisplayedCourses()
        
      } catch (error) {
        console.error('加载数据错误:', error)
        ElMessage.error('加载数据失败，请稍后重试')
      }
    },
    updateDisplayedCourses() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.displayedCourses = this.filteredCourses.slice(start, end)
    },
    filterCoursesByCategory(categoryId) {
      this.currentCategory = this.categories.find(cat => cat.id === categoryId) || null
      this.currentPage = 1
      this.updateDisplayedCourses()
    },
    getCategoryCourseCount(categoryId) {
      return this.courses.filter(course => course.categoryid === categoryId).length
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(cat => cat.id === categoryId)
      return category ? category.title : '未分类'
    },
    formatDate(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    goToCourseDetail(courseId) {
      this.$router.push(`/course/${courseId}`)
    },
    handleSort() {
      this.currentPage = 1
      this.updateDisplayedCourses()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.updateDisplayedCourses()
    },
    handleCurrentChange(current) {
      this.currentPage = current
      this.updateDisplayedCourses()
    }
  }
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}



/* 主内容区样式 */
.main-content {
  flex: 1;
  max-width: 1200px;
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}

/* 信息卡片 */
.info-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-bottom: 30px;
  text-align: center;
}

.site-title {
  font-size: 32px;
  color: #303133;
  margin-bottom: 10px;
}

.site-description {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

.repository-info {
  font-size: 14px;
  color: #909399;
}

.repository-info a {
  color: #409eff;
  text-decoration: none;
}

.repository-info a:hover {
  text-decoration: underline;
}

/* 分类部分 */
.categories-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.category-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #409eff;
}

.category-icon {
  width: 50px;
  height: 50px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  margin: 0 auto 15px;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.course-count {
  font-size: 14px;
  color: #606266;
}

/* 课程部分 */
.courses-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.course-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #409eff;
}

.course-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.course-card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 10px;
}

.course-badge {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.course-card-body {
  margin-bottom: 15px;
}

.course-info {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.course-info i {
  margin-right: 5px;
}

.course-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.author-name {
  font-size: 14px;
  color: #909399;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 页脚 */
.footer {
  background-color: #fff;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #e6e6e6;
  margin-top: auto;
}

.footer p {
  margin: 5px 0;
  color: #909399;
  font-size: 14px;
}

.footer a {
  color: #409eff;
  text-decoration: none;
}

.footer a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .categories-grid,
  .courses-grid {
    grid-template-columns: 1fr;
  }
  
  .site-title {
    font-size: 24px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .el-select {
    margin-top: 10px;
    width: 100%;
  }
}
</style>